import 'package:bluetooth_flutter_plugin/bluetooth_flutter_plugin.dart';
import 'package:bluetooth_flutter_plugin/src/bluetooth_helper/handler_bluetooth_device.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';

class ServiceCharacteristicsAdapter<T extends BluetoothAdapterBase> {
  final BluetoothDevice device;
  final List<BluetoothService> services;
  final T bluetoothAdapter;

  // 构造函数
  ServiceCharacteristicsAdapter(
    this.device,
    this.bluetoothAdapter,
    this.services,
  );

  // 处理蓝牙设备
  final HandlerBluetoothDevice _handlerBluetoothDevice =
      HandlerBluetoothDevice();

  // 查找蓝牙适配器服务和特征
  Future<HandlerBluetoothDevice> adapter() async {
    _handlerBluetoothDevice.device = device;

    // 查找通知服务
    var notifyService = await _findService(bluetoothAdapter.notifyServiceUuid);
    _handlerBluetoothDevice.bluetoothNotifyService = notifyService;

    // 查找通知特征
    var notifyCharacteristic = await _findCharacteristic(
      notifyService,
      bluetoothAdapter.notifyCharacteristicUuid,
    );
    _handlerBluetoothDevice.bluetoothNotifyCharacteristic =
        notifyCharacteristic;

    // 监听通知特征的变化
    var notifyStream = await _listenToCharacteristic(notifyCharacteristic);
    _handlerBluetoothDevice.notifyStream = notifyStream;

    // 查找写服务
    var writeService = await _findService(bluetoothAdapter.writeServiceUuid);
    _handlerBluetoothDevice.bluetoothWriteService = writeService;

    // 查找写特征
    var writeCharacteristic = await _findCharacteristic(
      writeService,
      bluetoothAdapter.writeCharacteristicUuid,
    );
    _handlerBluetoothDevice.bluetoothWriteCharacteristic = writeCharacteristic;

    // 效验设备连接是否成功
    if (_handlerBluetoothDevice.bluetoothNotifyService == null ||
        _handlerBluetoothDevice.bluetoothNotifyCharacteristic == null ||
        _handlerBluetoothDevice.bluetoothWriteService == null ||
        _handlerBluetoothDevice.bluetoothWriteCharacteristic == null) {
      throw Exception('Device connection failed');
    }

    return Future(() => _handlerBluetoothDevice);
  }

  // 查找服务
  Future<BluetoothService> _findService(Guid serviceUuid) {
    return Future(
      () => services.firstWhere(
        (service) => service.uuid == serviceUuid,
        orElse: () => throw Exception('Service not found'),
      ),
    );
  }

  // 查找特征值
  Future<BluetoothCharacteristic> _findCharacteristic(
    BluetoothService service,
    Guid characteristicUuid,
  ) {
    return Future(
      () => service.characteristics.firstWhere(
        (c) => c.uuid == characteristicUuid,
        orElse: () => throw Exception('Characteristic not found'),
      ),
    );
  }

  // 订阅通知
  Future<Stream<List<int>>> _listenToCharacteristic(
      BluetoothCharacteristic characteristic) async {
    try {
      await characteristic.setNotifyValue(true);
      return characteristic.lastValueStream;
    } catch (e) {
      throw Exception('Notification setup failed: ${e.toString()}');
    }
  }
}
